package org.example.ddm;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IShellOutputReceiver;

public class AdbFileLister2 {
    public static void main(String[] args) {
        // 初始化 AndroidDebugBridge
        AndroidDebugBridge.init(false);
        AndroidDebugBridge bridge = AndroidDebugBridge.createBridge("adb", false);

        // 等待设备连接
        while (!bridge.hasInitialDeviceList()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 获取连接的设备
        IDevice[] devices = bridge.getDevices();
        if (devices.length == 0) {
            System.out.println("没有检测到任何设备。");
        } else {
            IDevice device = devices[0];
            System.out.println("连接的设备: " + device.getSerialNumber());

            // 获取文件列表
            try {
                String files = listFiles(device, "/storage/emulated/0/DCIM/");
                System.out.println(files);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            // 关闭 AndroidDebugBridge
            AndroidDebugBridge.terminate();
        } catch (Throwable e) {
        }
    }

    private static String listFiles(IDevice device, String path) throws Exception {
        // 创建一个 ShellOutputReceiver 来接收命令输出
        StringBuilder output = new StringBuilder();
        IShellOutputReceiver receiver = new IShellOutputReceiver() {

            @Override
            public void addOutput(byte[] data, int offset, int length) {
                output.append(new String(data, offset, length));
            }

            @Override
            public void flush() {
                //System.out.println("文件列表: \n" + output.toString());
            }

            @Override
            public boolean isCancelled() {
                return false;
            }
        };

        // 执行 shell 命令来列出文件
        String command = "ls -lh " + path;
        device.executeShellCommand(command, receiver);

        return output.toString();
    }
}
